import os
import cv2
import json
import glob
import numpy as np

path = ".\\deep_net\\video\\"
def color_region_from_labelme(file):
    # 读取原始图像
    img = cv2.imread(file)
    img = np.zeros([img.shape[0],img.shape[1],1])
    #img = np.ones([img.shape[0],img.shape[1],1])
    # img=img*255/2.
    # cv2.imwrite(path+"label\\3.jpg",img)
    # 读取Labelme标注文件
    with open(path+"json\\"+os.path.splitext(os.path.basename(file))[0]+".json", 'r') as f:
        annotation = json.load(f)
    shapes = annotation['shapes']

    for shape in shapes:
        points = shape['points']
        points = [(int(p[0]), int(p[1])) for p in points]
        # 定义作色颜色（这里使用红色，在OpenCV中为BGR格式的[0, 0, 255]）
        color = [255, 255, 255]
        if shape['shape_type'] == 'polygon':
            cv2.fillPoly(img, [np.array(points)], color)
        if shape['shape_type']=='line' or shape["shape_type"]=="linestrip":
            for i in range(len(points)-1):
                cv2.line(img, points[i],points[i+1],color,20)      
    cv2.imwrite(path+"label\\"+os.path.splitext(os.path.basename(file))[0]+".jpg",img)

path = ".\\deep_net\\video\\"
def show_from_labelme(file):
    # 读取原始图像
    img = cv2.imread(file)
    mask = cv2.imread(path+"label\\"+os.path.splitext(os.path.basename(file))[0]+".jpg")
    result = cv2.hconcat([img,cv2.bitwise_and(img,mask)])
    cv2.imshow("",result)
    cv2.waitKey(1000)
    
def resize(file):
    img = cv2.imread(file)
    img = cv2.resize(img,(img.shape[0],img.shape[1]))
    cv2.imwrite(file,img)
    
def delfile():
    for file in glob.glob(path+"*-label.jpg"):
        os.remove(file)    
    
if __name__ == '__main__':
    #resize(file)
    #delfile()
    for file in glob.glob(path+"image\\*.jpg"):
        color_region_from_labelme(file)
        #show_from_labelme(file)